package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
        //判断缓存是否有
        List<String> range = stringRedisTemplate.opsForList().range("cache:shop:type", 0, -1);
        //判断是否为空
        if (range != null && range.size() > 0) {

            List<ShopType> listOfShopType = range.stream()
                    .map(item -> JSONUtil.toBean(item, ShopType.class))
                    .collect(Collectors.toList());

            return Result.ok(listOfShopType);
        }
        //为空查询数据库
        List<ShopType> shopType = query().orderByAsc("sort").list();

        //如果数据库为空
        if (shopType == null) {
            return Result.fail("未查询的店铺类型");
        }
        //转为对应类型
        List<String> jsonCollectionShops = shopType.stream().map(JSONUtil::toJsonStr).collect(Collectors.toList());
        //存入缓存
        stringRedisTemplate.opsForList().rightPushAll("cache:shop:list", jsonCollectionShops);
        return Result.ok(shopType);
        /**
         * string 类型做缓存 ： 查从来是string 转为对象类型
         * list 类型做缓存 ： 查出来是list(string) 转为list(对象)
         * hash 类型做缓存 : 查出来map(object,object) 转为对象类型 存到缓存是map(string,object)
         */
    }
}
